<template>
  <div class="user-container" style="height: 100%;">
      <div style="margin-top: 15px;" v-show="searchFromShow" class="search-container">
        <el-form class="search-form" label-width="80px"
                 ref="searchFormRef" :model="searchModel"
                 label-suffix=":">
          <el-row>
            <el-col :xs="24" :sm="12" :md="8" :lg="4">
              <el-form-item label="用户名" prop="userName">
                <el-input style="width: 100%" v-model="searchModel.userName" placeholder="请输入用户名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="4">
              <el-form-item label="姓名" prop="realName">
                <el-input style="width: 100%" v-model="searchModel.realName" placeholder="请输入姓名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item label-width="16px">
                <el-button type="primary" icon="el-icon-search" @click="selectUserListHandler">搜索</el-button>
                <el-button type="warning" icon="el-icon-refresh" @click="searchResetHandler">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <el-row class="toolbar-container" style="margin-top: 15px;">
        <el-col class="toolbar-left" :xs="20" :sm="18" :md="16">
          <el-button type="primary" icon="el-icon-circle-plus-outline" @click="insertUserHandler">新增</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="batchDeleteUserHandler"
                     :disabled="selectionDataSource.length <= 0">批量逻辑删除
          </el-button>
          <el-button type="danger" icon="el-icon-delete" @click="batchDeleteHandler"
                     :disabled="selectionDataSource.length <= 0">批量物理删除
          </el-button>
          <el-button icon="el-icon-delete" type="warning" @click="clearSelectionHandler"
                     :disabled="selectionDataSource.length <= 0">清除选择
          </el-button>
        </el-col>
        <el-col class="toolbar-right" :xs="4" :sm="6" :md="8">
          <el-row type="flex" justify="end">
            <el-button icon="el-icon-refresh" type="warning" @click="reload" circle
                       style="margin-right: 5px;"></el-button>
            <el-button icon="el-icon-search" type="primary" circle @click="showSearchModel"></el-button>
          </el-row>
        </el-col>
      </el-row>


      <div class="content-container" v-loading="loading" element-loading-text="拼命加载中"
           element-loading-spinner="el-icon-loading">
        <el-table
            height="100"
          v-table-height-adaptive="{bottomOffset: metadataModel.bottomOffset}"
          stripe
          ref="dataTableRef"
          row-key="userId"
          @selection-change="selectionChangeHandler"
          @sort-change="sortChangeHandler"
          :data="dataSource">
          <el-table-column
            type="index"
            label="序号"
            align="center"
            width="50">
          </el-table-column>
          <el-table-column
            type="selection"
            reserve-selection
            align="center"
            width="50">
          </el-table-column>
          <el-table-column
            prop="orgCode"
            label="组织编码"
            width="180">
          </el-table-column>
          <el-table-column
            prop="userName"
            label="用户名"
            width="180">
          </el-table-column>
          <el-table-column
            prop="realName"
            label="姓名"
            width="180">
          </el-table-column>
          <el-table-column
            prop="mobileNo"
            label="手机号码"
            width="180">
          </el-table-column>
          <el-table-column
            min-width="180"
            label="操作"
            fixed="right"
            align="center">
            <template #default="{ row, column, $index }">
              <el-button @click="updateUserHandler(row)" icon="el-icon-edit">编辑</el-button>
              <template>
                <el-popconfirm
                  style="margin-left: 8px"
                  confirm-button-text='确定'
                  cancel-button-text='取消'
                  icon="el-icon-info"
                  placement="top"
                  icon-color="red"
                  title="确定删除该行数据吗？"
                  @onConfirm="deleteUserHandler(row , column , $index)"
                >
                  <el-button slot="reference" type="danger" icon="el-icon-delete">逻辑删除</el-button>
                </el-popconfirm>
              </template>
              <template>
                <el-popconfirm
                  style="margin-left: 8px"
                  confirm-button-text='确定'
                  cancel-button-text='取消'
                  icon="el-icon-info"
                  placement="top"
                  icon-color="red"
                  title="确定删除该行数据吗？"
                  @onConfirm="deleteUser(row , column , $index)"
                >
                  <el-button slot="reference" type="danger" icon="el-icon-delete">物理删除</el-button>
                </el-popconfirm>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage4"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <insert-dialog ref="insertDialog" @insertSuccessEvent="selectUserListHandler"/>
      <update-dialog ref="updateDialog" @updateSuccessEvent="selectUserListHandler"/>
    </div>

</template>

<script>

  import {userList, deleteUserByUserId, deleteUser, deleteUserListApi, deleteUserList, userPageList} from '@/api/user'
  import insertDialog from './insert-dialog';
  import updateDialog from './update-dialog';
  import tableHeightAdaptiveDirective from '@/directive/el-table-height-adaptive'
  import tableMixin from '@/mixins/el-table'

  export default {
    name: "index",
    components: {
      insertDialog,
      updateDialog,
    },
    mixins: [tableMixin],

    directives: {
      tableHeightAdaptive: tableHeightAdaptiveDirective
    },
    data() {
      return {
        metadataModel: {
          bottomOffset: 56,
        },
        total: 0,
        pageSize: 10,
        pageNum: 1,
        currentPage4: 1,
        loading: false,
        searchFromShow: false,
        dataSource: [],
        selectionDataSource: [],
        searchModel: {
          userName: '',
          realName: '',
        }

      }
    },
    mounted() {
      this.selectUserListHandler()
    },
    methods: {
      handleSizeChange(val) {
        this.pageSize = val;
        this.selectUserListHandler();
      },
      handleCurrentChange(val) {
        this.pageNum = val;
        this.selectUserListHandler()
      },
      /**
       * 获取用户列表
       */
      selectUserListHandler() {
        this.loading = true;
        let params = {
          userName: this.searchModel.userName,
          realName: this.searchModel.realName,
          pageNum: this.pageNum,
          pageSize: this.pageSize,
        }
        userPageList(params).then(result => {
          this.total = result.totalSize;
          this.dataSource = result.data;
          this.loading = false;
        })
        // userList(params).then(result => {
        //   if (result) {
        //     this.dataSource = result.data;
        //     this.loading = false;
        //   }
        // })
      },
      //重置查询条件
      searchResetHandler() {
        this.searchModel.userName = '';
        this.searchModel.realName = '';
      },
      //刷新页面操作
      reload() {
        this.searchModel.userName = '';
        this.searchModel.realName = '';
        this.selectUserListHandler()
        this.clearSelectionHandler();
      },
      //显示搜索框
      showSearchModel() {
        this.searchFromShow = !this.searchFromShow;
      },
      /**
       * 多选操作
       * @param selection
       */
      selectionChangeHandler(selection) {
        this.selectionDataSource = selection
      },
      /**
       * 排序操作
       */
      sortChangeHandler({column, prop, order}) {
        console.log(column)
        console.log(prop)
        console.log(order)
      },
      /**
       * 清除多选操作
       */
      clearSelectionHandler() {
        this.$refs['dataTableRef'].clearSelection()
      },
      /**
       * 逻辑删除用户
       */
      deleteUserHandler(row, column, index) {
        let userId = row.userId;
        if (!userId) {
          return
        }
        deleteUserByUserId({userId}).then(response => {
          if (response.result) {
            this.$message({
              type: 'success',
              message: '逻辑删除成功！'
            });
            this.reload();
            this.clearSelectionHandler();
          }
        }).catch(error => {
        })
      },
      //物理删除用户
      deleteUser(row, column, index) {
        let userId = row.userId;
        if (!userId) {
          return;
        }
        deleteUser({userId}).then(response => {
          if (response.result) {
            this.$message({
              type: 'success',
              message: '物理删除成功！'
            });
            this.reload();
            this.clearSelectionHandler();
          }
        }).catch(error => {

        })
      },
      /**
       * 批量逻辑删除用户
       */
      batchDeleteUserHandler() {
        let length = this.selectionDataSource.length || 0
        if (length <= 0) {
          return this.$notify.warning("暂未选择任何数据，无法进行操作")
        }
        this.$confirm('确定逻辑删除 ' + length + ' 条数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let userIdList = this.selectionDataSource.map((element) => element.userId);
          deleteUserListApi({userIdList: userIdList}).then(response => {
            if (response.result) {
              this.$message({
                type: 'success',
                message: '批量逻辑删除成功！'
              });
              this.reload();
              this.clearSelectionHandler();
            }
          }).catch(error => {

          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //批量物理删除用户
      batchDeleteHandler() {
        let length = this.selectionDataSource.length || 0;
        if (length <= 0) {
          return this.$notify.warning("暂未选择任何数据，无法进行操作")
        }
        this.$confirm('确定物理删除 ' + length + ' 条数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let userIdList = this.selectionDataSource.map((element) => element.userId);
          deleteUserList({userIdList: userIdList}).then(response => {
            if (response.result) {
              this.$message({
                type: 'success',
                message: '批量物理删除成功！'
              });
              this.reload();
              this.clearSelectionHandler();
            }
          }).catch(error => {

          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //新增用户处理
      insertUserHandler() {
        this.$refs['insertDialog'].enabledDialogHandler();
      },
      //编辑用户处理
      updateUserHandler(user) {
        if (user) {
          this.$refs['updateDialog'].setUserModelHandler(user)
          this.$refs['updateDialog'].enabledDialogHandler()
        }
      },
    },
    watch: {
      'searchFromShow': {
        handler: function (val, oldVal) {
          // 每次处理搜索表单的display时更新表格动态高度
          this.setTableHeightAdaptiveHandler(this.$refs['dataTableRef'], this.metadataModel.bottomOffset)
        }
      },
    }
  }
</script>

<style lang="scss" scoped>

  .user-container {

    .search-container {
      background: white;
      padding: 3px 17px 0 17px;
      margin-bottom: 3px;

      .search-form {

        .el-form-item {
          margin-bottom: 0;
        }

        .el-col {
          margin-bottom: 3px;
        }

      }
    }

    .toolbar-container {
      background-color: white;
      padding: 3px 17px;

      .toolbar-right .el-button {
        margin-left: 10px;
      }

      .el-col {
        margin-bottom: 3px;
      }

    }


  }


</style>
